# Configure the HuaweiCloud Provider
terraform {
  required_providers {
    huaweicloud = {
      source = "local-registry/huaweicloud/huaweicloud"
      version = "= 1.34.1"
    }
  }
}

provider "huaweicloud" {
  region     = "cn-north-4"
  access_key = var.ak
  secret_key = var.sk
}

#Get ecs instances 
data "huaweicloud_compute_instances" "test" {}

#Get the ecs instances that has been backed up
data "huaweicloud_cbr_vaults" "test" {
  type = "server"
}

locals {
   ecs_ids    = data.huaweicloud_compute_instances.test.instances[*].id
  
  server_ids = data.huaweicloud_cbr_vaults.test.vaults[*].resources[*].server_id
  
  ecs_cbr_id = setsubtract(local.ecs_ids,flatten(local.server_ids))
}

#Create a backup policy,UTC time
resource "huaweicloud_cbr_policy" "test" {
  name        = "${var.template_name}-policy"
  type        = "backup"
  time_period = var.time_period
  backup_cycle {
    interval        = var.interval
    execution_times = ["19:00"]
  }
}

#Create a server type vault
resource "huaweicloud_cbr_vault" "test" {
  name             = "${var.template_name}-cbr"
  type             = "server"
  protection_type  = "backup"
  consistent_level = "crash_consistent"
  size             = var.storage_size
  auto_expand      = true
  policy_id        = huaweicloud_cbr_policy.test.id
  
  dynamic "resources"{
    for_each = local.ecs_cbr_id
	content{
		server_id = resources.value
	  }
  }
  tags = {
    foo = "bar"
  }
}










